package com.example.dynamicdatabase.dynamicconfig;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description 动态加载数据源
 * @Author 奶茶
 * Created by on 2018/11/25 9:50.
 */
public class DynamicDataBaseSource extends AbstractRoutingDataSource{

    private static DynamicDataBaseSource instance;
    private static byte[] lock=new byte[0];
    private Map<Object,Object> dataSourceMap = new HashMap<>();

    @Override
    public void setTargetDataSources(Map<Object, Object> targetDataSources) {
        super.setTargetDataSources(targetDataSources);
        dataSourceMap.putAll(targetDataSources);
        super.afterPropertiesSet();
    }

    /**
     * 确认当前数据库
     * @return
     */
    @Override
    protected String determineCurrentLookupKey() {
        return DBContextHolder.getDbType();
    }

    public Map<Object, Object> getDataSourceMap() {
        return dataSourceMap;
    }

    public static synchronized DynamicDataBaseSource getInstance(){
        if(instance==null){
            synchronized (lock){
                if(instance==null){
                    instance=new DynamicDataBaseSource();
                }
            }
        }
        return instance;
    }
}
